package com.imooc.controller;


import com.imooc.pojo.Users;
import com.imooc.pojo.bo.UsersBo;
import com.imooc.service.UserService;
import com.imooc.utils.CookieUtils;
import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.MD5Utils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.logging.Log;
import org.n3r.idworker.strategy.DefaultWorkerIdStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
/**
 * @Author: hhh
 * @CreateTime: 2025-05-18
 * @Description: 用户表
 * @Version: 1.0
 */
@Tag(name = "注册登录", description = "用于注册登录的相关接口")
@RestController
@RequestMapping("/passport")
public class PassportController {


    @Autowired
    private UserService userService;
    Logger logger = LoggerFactory.getLogger(PassportController.class);


    @Operation(summary = "用户名是否存在", description = "检查用户名是否存在")
    @GetMapping("/usernameIsExist")
    public IMOOCJSONResult usernameIsExist(@RequestParam String username) {
        // 1.判断用户名不能为空
        if (StringUtils.isBlank(username)) {
            return IMOOCJSONResult.errorMsg("用户名不能为空");
        }
        // 2.查找注册的用户是否存在
        boolean isExist = userService.queryUsernameExist(username);
        if (isExist) {
            return IMOOCJSONResult.errorMsg("用户名已存在");
        }
        // 3.请求成功用户名没重复
       return IMOOCJSONResult.ok();
    }

    /**
     * 用户注册
     * @param usersBo
     * @return 用户注册实体
     */
    @Operation(summary = "用户注册", description = "用户注册")
    @PostMapping("/regist")
    public IMOOCJSONResult regist(@RequestBody UsersBo usersBo,HttpServletRequest request,
                                  HttpServletResponse response) {
        String username = usersBo.getUsername();
        String password = usersBo.getPassword();
        String confirmPwd = usersBo.getConfirmPassword();
        // 0.判断用户名和密码不能为空
        if (StringUtils.isBlank(username) ||
                StringUtils.isBlank(password) ||
                StringUtils.isBlank(confirmPwd)) {
            return IMOOCJSONResult.errorMsg("用户名或密码不能为空");
        }
        // 2. 判断密码长度不能少于6位
        if (password.length() < 6) {
            return IMOOCJSONResult.errorMsg("密码长度不能少于6位");
        }
        // 3. 判断两次密码输入是否一致
        if (!password.equals(confirmPwd)) {
            return IMOOCJSONResult.errorMsg("两次密码输入不一致");
        }
        // 1. 查询用户名是否存在
        boolean isExist = userService.queryUsernameExist(username);
        if (isExist) {
            return IMOOCJSONResult.errorMsg("用户名已经存在");
        }
        // 4. 注册
        Users userResult = userService.createUser(usersBo);
        // 5. 设置空属性
        userResult = setNullProperty(userResult);
        // 6.注册信息写入到cookie中
        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(userResult), true);
        // TODO 生成用户token，存入redis会话
        // TODO 同步购物车数据

        return IMOOCJSONResult.ok();
    }

    /**
     * 用户登录
     * @param usersBo
     * @return 用户登录实体
     */
    @Operation(summary = "用户登录", description = "用户登录")
    @PostMapping("/login")
    public IMOOCJSONResult login(@RequestBody UsersBo usersBo,  HttpServletRequest request,
                                 HttpServletResponse response)throws Exception{
        String username = usersBo.getUsername();
        String password = usersBo.getPassword();

        // 0. 判断用户名和密码必须不为空
        if (StringUtils.isBlank(username) ||
                StringUtils.isBlank(password)) {
            return IMOOCJSONResult.errorMsg("用户名或密码不能为空");
        }
        // 1. 实现登录
        Users userResult = userService.queryUserForLogin(username, MD5Utils.getMD5Str(password));

        if (userResult == null) {
            return IMOOCJSONResult.errorMsg("用户名或密码不正确");
        }

        userResult = setNullProperty(userResult);

        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(userResult), true);

        // TODO 生成用户token，存入redis会话
        // TODO 同步购物车数据

        return IMOOCJSONResult.ok(userResult);
    }

    private Users setNullProperty(Users userResult) {
        userResult.setPassword(null);
        userResult.setMobile(null);
        userResult.setEmail(null);
        userResult.setCreatedTime(null);
        userResult.setUpdatedTime(null);
        userResult.setBirthday(null);
        return userResult;
    }
}
